#!/bin/bash
# This script installs and runs lmbench
# All parameters are passed by environment variables
###SHELLPACK preamble lmbench-bench 3

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

###SHELLPACK check_install_required lmbench-${VERSION}
###SHELLPACK init_complete

cd $SHELLPACK_SOURCES/lmbench-${VERSION}-installed || die "Failed to cd to lmbench directory"
for LMBENCH_TEST in $LMBENCH_TESTS; do
	# Prepare test
	case $LMBENCH_TEST in
	lat_mmap)
		;;
	lat_ctx)
		echo
		;;
	*)
		die "Unrecognised test $LMBENCH_TEST for preparation"
		;;
	esac

	# Run test
	monitor_pre_hook $LOGDIR_RESULTS $LMBENCH_TEST
	LMBENCH_RESULTS=$LOGDIR_RESULTS/lmbench-${LMBENCH_TEST}.log

	case $LMBENCH_TEST in
	lat_mmap)
		STRIDE=$(((LMBENCH_LATMMAP_MAX_FILESIZE-LMBENCH_LATMMAP_MIN_FILESIZE)/4))
		for FILESIZE in `seq $LMBENCH_LATMMAP_MIN_FILESIZE $STRIDE $LMBENCH_LATMMAP_MAX_FILESIZE`; do
			mmtests_activity filesize $FILESIZE
			FILESIZE=$((FILESIZE&~4095))
			dd if=/dev/zero of=$SHELLPACK_DATA/lmbench.file ibs=4096 count=$((FILESIZE/4096)) conv=fsync 2> /dev/null
			for ITERATION in `seq 1 $LMBENCH_LATMMAP_ITERATIONS`; do
				./bin/$LMBENCH_TEST \
					-N 30 \
					$FILESIZE $SHELLPACK_DATA/lmbench.file \
						2>&1 | tee -a $LMBENCH_RESULTS
			done
		done
		rm $SHELLPACK_DATA/lmbench.file
		;;
	lat_ctx)
		LMBENCH_LATCTX_SIZE=`echo $LMBENCH_LATCTX_SIZE | tr ',' ' '`
		###SHELLPACK threads_large_stride_begin 2 $LMBENCH_LATCTX_MAXCLIENTS
			for SIZE in $LMBENCH_LATCTX_SIZE; do
				mmtests_activity size $SIZE
				echo mmtests-size:$SIZE >> ${LMBENCH_RESULTS}

				for ITERATION in `seq 1 $LMBENCH_LATCTX_ITERATIONS`; do
					echo Running with $NR_THREADS threads size $SIZE iter $ITERATION/$LMBENCH_LATCTX_ITERATIONS
					./bin/$LMBENCH_TEST \
						-s $SIZE \
						$NR_THREADS 2>&1 | tee -a ${LMBENCH_RESULTS}-${SIZE}-${NR_THREADS}-${ITERATION}.raw
				done
				MIN_ITER=`grep ^[0-9] ${LMBENCH_RESULTS}-${SIZE}-${NR_THREADS}-*.raw | sort -n -k 2 | head -1 | awk -F : '{print $1}'`
				if [ "$MIN_ITER" != "" ]; then
					echo min: $MIN_ITER
					cat $MIN_ITER | tee -a ${LMBENCH_RESULTS}
				else
					echo mmtests-no-samples: $NR_THREADS $SIZE | tee -a ${LMBENCH_RESULTS}
				fi
			done
		###SHELLPACK threads_stride_end
		;;
	*)
		die "Unrecognised test $LMBENCH_TEST for execution"
		;;
	esac
	monitor_post_hook $LOGDIR_RESULTS $LMBENCH_TEST 

	rm -f $SHELLPACK_DATA/lmbench.file 2> /dev/null
done

exit $SHELLPACK_SUCCESS
